package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func m1(c *gin.Context) {
	body, _ := c.GetRawData()
	fmt.Println("m1的数据：",string(body))
	fmt.Println("m1")
}

/*
func main() {
	router := gin.Default()
	router.POST("/", func(c *gin.Context) {
		type UserInfo struct {
			Name string `json:"name" binding:"sign" msg:"用户名错误"`
			Age  int    `json:"age" binding:""`
		}
		var user UserInfo
		err := c.ShouldBindJSON(&user)
		if err != nil {
			// 显示自定义的错误信息
			msg := GetValidMsg(err, &user)
			c.JSON(200, gin.H{"msg": msg})
			return
		}
		c.JSON(200, user)
	})
	// 注册
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("sign", signValid)
	}
	router.Run(":80")
}
func GetValidMsg(err error, obj interface{}) string {
	// obj为结构体指针
	getObj := reflect.TypeOf(obj)
	// 断言为具体的类型，err是一个接口
	if errs, ok := err.(validator.ValidationErrors); ok {
		for _, e := range errs {
			if f, exist := getObj.Elem().FieldByName(e.Field()); exist {
				return f.Tag.Get("msg") //错误信息不需要全部返回，当找到第一个错误的信息时，就可以结束
			}
		}
	}
	return err.Error()
}
*/


func main() {
	//postman : http://localhost:8080/api/hello
	router := gin.Default()
	r := router.Group("/api")
	r.Use(m1)

	r.GET("/hello", func(c *gin.Context) {
		fmt.Println("hello")
		c.JSON(200, gin.H{
			"message": "Hello World",
		})
	})

	r.GET("/world", func(c *gin.Context) {
		fmt.Println("world")
		c.JSON(200, gin.H{
			"message1": "World",
		})
	})

	//r.GET("/hello",  func(c *gin.Context) {
	//	person := Person{
	//		Age: 18,
	//		Name: "test",
	//	}
	//	c.JSON(http.StatusOK, person)
	//})

	err := router.Run(":8080")
	if err != nil {
		return
	}
}



type User struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

type Person struct {
	Name string `json:name`
	Age int `json:age`
}

func getUser(c *gin.Context) {
	name := c.Query("name")
	email := c.Query("email")

	c.JSON(http.StatusOK, gin.H{
		"name":  name,
		"email": email,
	})
}

func postUser(c *gin.Context) {
	var user User
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, user)
}